<template>
  <div class="accountPage">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-bank-card">  应用审核</i> 
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="addAccountBox" v-if="hasPerm('user:add')">
      <el-button type="primary" size="mini" @click="addAccount" >添加账号</el-button>
    </div>
    <div class="handle-box">
      <el-form :inline="true" :model="formInline" ref="userFormRefAccount" class="demo-form-inline">
        <el-form-item label="" prop="username">
          <el-input v-model="formInline.username" placeholder="用户账号"></el-input>
        </el-form-item>
        <el-form-item label="" prop="nickName">
          <el-input v-model="formInline.nickName" placeholder="用户名称"></el-input>
        </el-form-item>
        <el-form-item label="" prop="phone">
          <el-input v-model="formInline.phone" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item label= "状态 :"  >
         <el-select v-model="optionsValue" style="width:90px" clearable placeholder="状态">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
         </el-option>
        </el-select>
      </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onFindAccount">查询</el-button>
          <el-button type="success" @click="onBlank">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table class="accountTable" :data="list" height="400px" border>
      <el-table-column
        label="序号"
        width="60"
        align="center"
      >
       <template slot-scope="scope">
            {{scope.$index + 1}}
        </template></el-table-column>
      <el-table-column prop="username" label="用户账号" width="160" align="center"></el-table-column>
      <el-table-column prop="nickName" label="用户名称"  align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="160"  align="center"></el-table-column>
      <el-table-column label="创建日期" width="240" align="center">
        <template slot-scope="scope">
          {{scope.row.createTime | timeFormat}}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.available">
            正常
          </el-tag>
          <el-tag v-else type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260"  align="center"  v-if="hasPerm('user:upa') ||hasPerm('user:delete') ">
        <template slot-scope="scope">
          <el-button
           v-if="hasPerm('user:upa')"
            type="text"
            icon="el-icon-edit"
            class="btn-sz"
            @click="updateAccount(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
          v-if="scope.row.available && hasPerm('user:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'禁用')"
            >禁用</el-button
          >
          <el-button
          v-if="!scope.row.available && hasPerm('user:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'启用')"
            >启用</el-button
          >
          <el-button
          v-if="userId == '1' ? true : false"
            type="text"
            icon="el-icon-delete"
            class="blue btn-sz"
            @click="changePassword(scope.row)"
            >重置密码</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="queryInfo.pagenum"
          :page-size="queryInfo.pagesize"
          :total="pageTotal"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 对话框区域 -->
     <el-dialog v-dialogDrag width="500px" @close="blankAccount" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="tempAccount" status-icon  :rules="accountRule" ref="accountForm"   label-position="left" label-width="100px"  style='width: 460px; margin-left:20px; height:400px;'>
        <el-form-item prop="username" label="用户账号"  >
          <el-input :disabled="dialogStatus == 'update' ? true : false" v-model="tempAccount.username" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='create'" prop="password" show-password label="用户密码" >
          <el-input type="text" v-model="tempAccount.password" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item prop="nickName" label="账号名称" >
          <el-input type="text" v-model="tempAccount.nickName" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item prop="phone" label="手机号" >
          <el-input type="text" v-model="tempAccount.phone" style="width: 250px;">   
          </el-input>
        </el-form-item>
        <el-form-item  label="状态" required>
          <el-switch
          v-model="accountSwitch"
          active-text="启用"
          inactive-text="禁用"
          >
         </el-switch>
        </el-form-item>
        <el-form-item  label="选择角色" required>
          <template>
            <el-select
              v-model="roleListIdArr"
              multiple
              default-first-option
              placeholder="选择角色">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="blankAccount">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createAccount">创 建</el-button>
        <el-button type="primary" v-else @click="editAccount">修 改</el-button> 
      </div>
     </el-dialog>
     <el-dialog v-dialogDrag width="500px" :visible.sync="dialogPassword"  @close="blankPassword">
       <el-form :model="newPassword" :rules="accountRule" ref="passWordForm" label-position="left" label-width="100px"  style='width: 460px; margin-left:10px; '>
        <el-form-item prop="password"  label="新密码 :" >
          <el-input type="text" show-password v-model="newPassword.password" style="width: 250px;">
          </el-input>
        </el-form-item>
      </el-form> 
        <el-input v-model="newPassword.id"  v-show=false placeholder="请输入新密码"></el-input>
        <div slot="footer" class="dialog-footer">
        <el-button @click="blankPassword">取 消</el-button>
        <el-button type="success" @click="changePasswordBtn">确 定</el-button>
      </div>
     </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { commonGetUserList, commonGetUserListAdd, commonGetUserListUpa, commonRoleList, commongetAccountId, commonChangeStatu } from '../../../service/common.js'
export default {
  data() {
    return {
      roleListIdArrTwo:'',
      // 重置密码弹窗数据
      newPassword:{
        id:'',
        password:''
      },
      dialogPassword:false, //重置密码弹窗
      optionsValue:'2', //下拉框的值
      // 查询数据
      options: [
        {
          value: "0",
          label: "禁用",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "所有",
        },
      ],
      //规则
      accountRule: {
        username:[
           { required: true, message: '请输入用户名', trigger: 'blur' },
           { min: 2, max: 10, message: '长度在 2 到 10 字符', trigger: 'blur' }
        ],
        password:[
           { validator: this.validatePass,  required: true, trigger: 'blur' }
        ],
        nickName:[
           {  required: true, message: '请输入昵称', trigger: 'blur' },
           { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        phone:[
          { validator: this.validatePhone,  required: true, trigger: 'blur' }
        ]
      },
      queryInfo: {
        pagenum: 1,
        pagesize: 5,
      },
      dialogFormVisible:false, //对话框开关
       //对话框状态映射
      textMap: {
        update: '编辑账号',
        create: '新建账号'
      },
      dialogStatus:'create', //对话框状态
      tempAccount:{
        username:'', //账号
        password:'', //密码
        nickName:'', //昵称
        phone:'', //手机号
        available:'' //状态
      },
      accountSwitch:false, //状态
      roleList:[], //角色数组
      roleListIdArr:[], //角色id数组
      pageTotal: 0, //总页数
      // 查询数据
      formInline: {
        username: "",
        nickName: "",
        phone: "",
        available:''
      },
      // 表格数据
      list: [],
    };
  },
  created() {
    this.getAccountList()
    this.getRoleList()  
  },
  methods: {
    // 重置密码
    changePassword(row) {
      this.newPassword.id = row.id
      this.dialogPassword = true
    },
    // 重置密码
    changePasswordBtn() {
      this.$refs.passWordForm.validate(async (valid) => {
      if (valid) {
      try {
       const res = await commonChangePassword(this.newPassword)
       this.dialogPassword = false
       this.$message.success(res.msg)
       this.getAccountList()
       this.blankPassword()
      } catch (error) {
        this.$message.success(error)
        }
       }else {
          this.$message.error('error submit!!')
          return false
        }
      })
    },
    blankPassword() {
      this.newPassword.id = ''
      this.newPassword.password = ''
      this.dialogPassword = false
    },
    // 获取角色列表
    async getRoleList() {
      try {
      const res = await commonRoleList()
      if (res.code == '200') {
        this.roleList = res.sysUsers
      }
      } catch (error) {
        this.$message.success(error)
      }
    },
    // 获取账号列表
    async getAccountList() {
      const res = await commonGetUserList(this.queryInfo)
      if (res.code == '200') {
       this.list = res.sysUsers.records
       this.pageTotal = res.sysUsers.total
      }
      console.log('res: 获取账号列表', res);
    },
    // 添加账号接口
     createAccount() {
      this.$refs.accountForm.validate( async (valid) => {
     if (valid) {
      if (this.accountSwitch) {
        this.tempAccount.available = 1
      }else {
        this.tempAccount.available = 0
      }
      this.tempAccount.roleIds = this.roleListIdArr.join(',') || ''
      console.log(this.tempAccount,'添加账号传参')
      try {
      const res = await commonGetUserListAdd(this.tempAccount)
      if(res.code == "200") {
        this.$message.success(res.msg);
        this.blankAccount()
        this.getAccountList()
      }else {
        this.$message.success(res.msg);
      }
      } catch (error) {
        this.$message.error('添加账号接口异常');
        this.$message.error(error);
      }
        }else {
          this.$message.error('error submit!!')
          return false
        }
      })

    },
    // 添加用户按钮
    addAccount() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 编译账号
    async editAccount() {
    this.$refs.accountForm.validate( async (valid) => { 
      if (valid) {
       if (this.accountSwitch) {
        this.tempAccount.available = 1
      }else {
        this.tempAccount.available = 0
      }
      this.tempAccount.roleIds = this.roleListIdArr.join(',') || ''
            console.log(this.tempAccount,'编译账号传参')
      try {
      const res = await commonGetUserListUpa(this.tempAccount)
      if(res.code == "200") {
        this.$message.success(res.msg);
        this.blankAccount()
        this.getAccountList()
      }else {
        this.$message.success(res.msg);
      }
      } catch (error) {
        this.$message.error('编译账号接口异常');
        this.$message.error(error);
      }
      }else {
          this.$message.error('error submit!!')
          return false
        }
    }
    )
    },
    // 编译按钮
    async updateAccount(index,row) {
      console.log(row,index)
      try {
        const res = await commongetAccountId({id:row.id})
        console.log('res:根据id返回ids ', res);
         let idsArr
        if (res.data.roleIds.length == 0) {
          idsArr = []
        }else {
          idsArr = res.data.roleIds.split(',')
        }
        this.roleListIdArr = idsArr.map(Number)
        console.log('this.roleListIdArr: ', this.roleListIdArr);
        this.tempAccount.username = row.username
        this.tempAccount.password = row.password
        this.tempAccount.nickName = row.nickName
        this.tempAccount.phone = row.phone
        this.tempAccount.available = row.available
        this.tempAccount.id = row.id
        if (row.available == 1) {
          this.accountSwitch = true
        }else {
          this.accountSwitch = false
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      } catch (error) {
        this.$message.error('异常操作')
        console.log(error,'异常操作error')
      }

    },
    // 点击取消弹窗 
    blankAccount() {
      this.tempAccount.username = ''
      this.tempAccount.password = ''
      this.tempAccount.nickName = ''
      this.tempAccount.phone = ''
      this.tempAccount.available = ''
      this.roleListIdArr.length = 0
      this.roleListIdArr = []
      this.dialogStatus = 'create'
      console.log('this.dialogStatus: ', this.dialogStatus);
      console.log('改变了dialog')
      this.accountSwitch = false
      this.dialogFormVisible = false
    },
    // 查询
    async onFindAccount() {
      if (this.optionsValue == '2') {
       this.formInline.available = ''
      }else if (this.optionsValue == '1') {
        this.$set(this.formInline,'available',1)
      }else {
        this.$set(this.formInline,'available',0)
      }
      try {
      const res = await commonGetUserList(this.formInline)
      if (res.code == '200') {
       this.list = res.sysUsers.records
       this.pageTotal = res.sysUsers.length
      }
      } catch (error) {
         this.$message.success(error)
      }
    },
    // 重置
    onBlank() {
      this.optionsValue = '2'
      this.$refs.userFormRefAccount.resetFields()
      this.getAccountList()
      this.getRoleList()
    },
        // 删除操作
    changeStatu(row,state) {
      let available 
      if (row.available) {
        available = 0
      }else {
        available = 1
      }
        // 二次确认删除
        this.$confirm(`确定要${state}吗？`, '提示', {
            type: 'warning'
        })
        .then(async () => {
           let param = {
            id:row.id,
            available: available
           }
            await commonChangeStatu(param)
            this.$message.success(`${state}成功`);
            this.getAccountList()
        })
        .catch(() => {});
    },
      // 分页导航
    handlePageChange(val) {
      this.$set(this.queryInfo, 'pagenum', val);
      this.getAccountList()
    },
        // 检查手机号
    validatePhone(rule, value, callback) {
      if (value.trim().length == 0) {
        return callback(new Error('手机号不能为空'));
      }else {
        if (this.checkPhone(value.trim())) {
          callback()
        }else {
          return callback(new Error('请输入有效的手机号码！'));
        }
      }
      return callback(new Error(this.checkPhone(value)));
    },
    // 手机号格式校验
    checkPhone(phone) {
      console.log(phone,'phone')
      if (phone.trim().length == 0) {
        return callback(new Error('手机号不能为空'));
      } else {
        let myreg = /^1(3|4|5|6|7|8|9)\d{9}$/;
        if (!myreg.test(phone)) {
          return false
        }else {
          return true
        }
      }
    },
    // 检查密码
    checkPassWord(value) {
      let pattern = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*])[\da-zA-Z~!@#$%^&*]{8,}$/;
      let pass = this.lxStr(value)
      if(!pattern.test(value) || !pass) {
        return false
      }else {
        return  true
      }
    },
     lxStr(str){
   var arr = str.split('');
   var flag = true;
   for (var i = 1; i < arr.length-1; i++) {
      var firstIndex = arr[i-1].charCodeAt();
      var secondIndex = arr[i].charCodeAt();
      var thirdIndex = arr[i+1].charCodeAt();
      thirdIndex - secondIndex == 1;
      secondIndex - firstIndex==1;
      if((thirdIndex - secondIndex == 1)&&(secondIndex - firstIndex==1)){
         flag =  false;
      }
   }
   return flag;
   },
    // 密码校验
    validatePass(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入密码'));
      }else {
        if (this.checkPassWord(value)) {
          callback()
        }else {
          return callback(new Error('密码校验失败'));
        }
      }
    },
  },
  computed: {
     ...mapGetters(["userId"]),
  }
};
</script>

<style lang="less" scoped>
.accountPage {
  min-width: 100%;
  height: 100%;
  border-radius: 5px;
  padding-top: 15px;
  padding-left: 20px;
  background-color: #fff;

  .accountTable {
    width: 100%;
    max-height: 62%;
    overflow: auto;
  }

  .handle-box {
    margin-top: 10px;
    margin-bottom: 0px!important;
  }

  // .addAccountBox {
  //   height: 80px;
  //   padding: 20px 0 20px 0;
  // }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }

 .pagination {
   margin: 20px 0;
   text-align: right;
 }

}
</style>